const Base = require("./base");
module.exports = class ShareService extends Base {
  list() {
    let sql = `SELECT id,\`name\`,\`describe\` FROM product_classify WHERE id=8;
    SELECT * FROM product WHERE pro_id=8 ORDER BY sort=0,sort`;
    return this.app.mysql
      .use("foindia")
      .query(sql)
      .then((res) => res[0])
      .then((res) => {
        const data = res[0][0] || {};
        data.children = res[1];
        return data;
      });
  }

  exchangeCode(params) {
    const { exchange_uid, code } = params;
    let sql = `SELECT * FROM exchange_code WHERE code='${code}'`;
    const DB = this.app.mysql.use("foindia");
    return DB.query(sql)
      .then((res) => res[0][0])
      .then((data) => {
        if (data) {
          if (data.uid === exchange_uid) {
            // 自己不能领自己的
            return {
              data,
              status: 1,
            };
          } else {
            if (data.exchange_uid) {
              // 已经兑换过了
              return {
                data,
                status: 2,
              };
            }
            const { replacements, values } = this.installParams(
              { exchange_uid },
              2
            );
            const sql = `UPDATE exchange_code SET ${values} WHERE code='${code}'`;
            return DB.query(sql, { replacements }).then(() => ({
              data,
              status: 0,
            })); // 兑换成功
          }
        } else {
          return {
            status: -1,
          }; // 找不到code
        }
      });
  }

  createCode(params) {
    const { keys, replacements, values } = this.installParams(params);
    let sql = `INSERT INTO exchange_code(${keys}) VALUES(${values})`;
    return this.app.mysql
      .use("foindia")
      .query(sql, {
        replacements,
      })
      .then((res) => res[0]);
  }

  exchangeCodePage(params) {
    const { id } = params;
    let sql = `SELECT * FROM exchange_code WHERE id=${id};`;
    const DB = this.app.mysql.use("foindia");
    return DB.query(sql)
      .then((res) => res[0][0])
      .then(async (res) => {
        if (res) {
          const { pro_id } = res;
          let sql = `SELECT * FROM product WHERE id=${pro_id};`;
          return DB.query(sql)
            .then((res) => res[0][0])
            .then((res2) => {
              return Object.assign(res2, res);
            });
        }
        return null;
      });
  }

  exchangeList(uid) {
    let sql = `SELECT b.*,a.* FROM exchange_code as a RIGHT JOIN product as b ON a.pro_id=b.id WHERE a.exchange_uid='${uid}';`;
    return this.app.mysql
      .use("foindia")
      .query(sql)
      .then((res) => res[0]);
  }
};
